package com.yycx.starter.redis.listener;


import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.starter.redis.core.RedisKeyChangeListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @authorzyf
 * @createTime
 */
@Component
public class RedisKeyChangeHandler implements MessageListener {

    /**
     * 监听redis key前缀
     */
    public static final String TOPIC_KEY_SPACE_PRE = "__keyspace@0__:";

    /**
     * 表示只监听所有的key
     */
    private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("__keyevent@*");
    /**
     * 表示只监听所有的key
     */
    private static final Topic TOPIC_KEYEVENTS_SET = new PatternTopic("__keyevent@0__:set");
    /**
     * 不生效
     */
    public static final Topic TOPIC_KEYNAMESPACE_NAME = new PatternTopic("__keyspace@0__:mimio_upload");
    public static final Topic TOPIC_KEYNAMESPACE_NAME2 = new PatternTopic("__keyspace@0__:UPLOAD:FILETYPE");
    /**
     * 监控
     */
    private static final Topic TOPIC_KEYEVENTS_NAME_SET_USELESS = new PatternTopic("__keyevent@0__:set myKey");

    @Autowired(required = false)
    private Map<String, RedisKeyChangeListener> redisMessageListenerMap;

    private Integer num = 0;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    @Override
    public synchronized void onMessage(Message message, byte[] pattern) {
        String key = new String(pattern, Charset.forName("utf-8"));
        if (FlymeUtils.isNotEmpty(redisMessageListenerMap)) {
            byte[] body = message.getBody();
            String result = new String(body, Charset.forName("utf-8"));
            com.yycx.starter.redis.core.RedisKeyChangeListener redisMessageListener = null;
            for (Map.Entry<String, com.yycx.starter.redis.core.RedisKeyChangeListener> entry : redisMessageListenerMap.entrySet()) {
                com.yycx.starter.redis.core.RedisKeyChangeListener listener = entry.getValue();
                String topic = com.yycx.starter.redis.listener.RedisKeyChangeHandler.TOPIC_KEY_SPACE_PRE + listener.getTopicName();
                if (topic.equals(key)) {
                    redisMessageListener = listener;
                }
            }
            Boolean check = redisTemplate.hasKey(key+":check");
            if (FlymeUtils.isNotEmpty(redisMessageListener) && check == false) {
                redisMessageListener.onSuccess(result, key);
                redisTemplate.opsForValue().set(key+":check",1, 100, TimeUnit.MILLISECONDS);
            }
        }
    }

}

